package downloader

import (
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/downloader"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type DownloadRequest struct {
	Id string `form:"id" validate:"required" binding:"required,uuid"` // 任务ID
}

func (cls *Downloader) Download(c *gin.Context) {
	var body = DownloadRequest{}
	if err := c.ShouldBindQuery(&body); nil != err {
		c.AbortWithStatus(http.StatusBadRequest)

		return
	}

	var task, ok = cls.downloader.GetTask(body.Id)
	if !ok {
		c.AbortWithStatus(http.StatusNotFound)

		return
	}

	if downloader.TaskStateComplete != task.State {
		c.AbortWithStatus(http.StatusNotFound)

		return
	}

	// 资源管理器
	if downloader.TaskTargetResources == task.Target {
		path, err := cls.resources.AbsFilepath(task.SavePath, task.Filename)
		if nil != err {
			c.AbortWithStatus(http.StatusInternalServerError)

			return
		}

		c.FileAttachment(path, task.Filename)

		return
	}

	// 临时文件
	if downloader.TaskTargetTemporary == task.Target {
		if time.Now().Unix() >= task.EndTime.Add(task.Timeout).Unix() {
			c.AbortWithStatus(http.StatusNotFound)

			return
		}

		c.FileAttachment(task.LocalFilepath, task.Filename)

		return
	}

	c.AbortWithStatus(http.StatusNotFound)
}
